var util = require('./util.js');
var app = getApp();
var HOST;

/**
 * get请求
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function _Get(params) {
  params = params || {};
  params.method = 'get';
  _request(params);
}

/**
 * post请求
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function _Post(params) {
  params = params || {};
  params.method = 'post';
  _request(params);
}

/**
 * 异步请求基础方法
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function _request(params) {
  var {
    method,
    url,
    data,
    success,
    fail,
    iHandleFail
  } = params;
  var userSid = app.getUserSid();
  var alias = app.getAlias();
  var employee_sid = app.getEmployeeSid();
  var sid = app.globalData.sid;
  var requestObj;
  var header = {};

  HOST = app.getHost();

  method = (method || 'get').toLowerCase();
  url += '?alias=' + alias;
  if (employee_sid){
    url += '&employee_sid=' + employee_sid;
  }
  data = data || {};
  data.userSid = userSid;
  data.sid = sid;

  if (method == 'post') {
    header = {
      'content-type': 'application/x-www-form-urlencoded',
    }
  }

  // console.log('---req url:', HOST, url);
  requestObj = {
    url: HOST + url,
    header: header,
    method: method,
    success: function(res) {
      var data = res.data;

      if (data.code == 0) {
        typeof success == "function" && success(data);
      } else {
        typeof fail == "function" && fail(data);
        if (iHandleFail) {
          return;
        }
        if (data.code == 107) {
          wx.navigateTo({
            url: '/pages/login/index'
          });
        } else {
          if (data.msg) {
            util.alert(data.msg);
          }
        }
      }
    },
    fail: function(res) {
      // console.log('---req fail:', res);
      typeof fail == "function" && fail(res);
    }
  };

  requestObj.data = data;

  wx.request(requestObj);
}

module.exports = {
  P: _Post,
  G: _Get,
  request: _request
}